<template>
  <div style="padding: 30px 0">
    <div class="formCon">
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="180px" label-position="left">
        <el-form-item label="原密码" prop="oldPassword" v-if="isPassword">
          <el-input v-model="formData.oldPassword" placeholder="请输入原密码" class="width30" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入新密码" class="width30" />
        </el-form-item>
        <el-form-item label="再次输入新密码" prop="passwordConfirm">
          <el-input v-model="formData.passwordConfirm" placeholder="请再次输入新密码"  class="width30" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="saveLoading" @click="save(ruleFormRef)">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import {ref, reactive, toRefs} from "vue";
import type { FormInstance, FormRules } from 'element-plus'
import {changePwd, userInfoApi} from '@/api/api'
import { useRouter } from "vue-router";
import {ElMessage} from "element-plus";
import {useSysStore} from "@/store/user";
const { userInfo } = toRefs(useSysStore());
const router = useRouter();
interface submitData {
  oldPassword:string;
  password: string;
  passwordConfirm: string;
}
const saveLoading = ref<boolean>(false)
const ruleFormRef = ref<FormInstance>()
let formData = ref<submitData>({
  oldPassword: '',
  password: '',
  passwordConfirm: ''
})
const isPassword = ref(false)
userInfoApi().then((res:any) => {
  isPassword.value = res.data.isPassword
})
const validatePsd = (rule:any, value:any, callback:any) => {
  if (value !== formData.value.password) {
    callback(new Error("两次输入密码不一致!"));
  } else {
    callback();
  }
}
const rules = reactive<FormRules<submitData>>({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  passwordConfirm: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {validator: validatePsd, trigger: 'blur' }
  ]
})
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      saveLoading.value = true
      changePwd(formData.value).then((res:any) => {
        saveLoading.value = false
        ElMessage.success('密码修改成功')
        setTimeout(() => {
          router.go(-1)
        }, 2000)
      }).catch((err:any) => {
        saveLoading.value = false
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
const cancel = () => {
  router.go(-1)
}
</script>
<style scoped>
.formCon{
  width: 60%;
  background: #fff;
  margin: 15px auto;
  padding: 30px;
  box-sizing: border-box;
}
.width30{
  width: 50%;
}

</style>